package com.xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice//切面
@ResponseBody
public class ExceptionCatch {

    public static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    //捕获处理可预知异常
    @ExceptionHandler(CustomeException.class)
    public ResponseResult throwKownException(CustomeException e){
        LOGGER.error("excetion...{}",e.getMessage());
        return new ResponseResult(e.getResultCode());
    }

    //创建Map,预存不可预知异常的提示信息和响应码
    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    //构建builder
    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    //静态代码块存放异常
    static {
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALIDPARAM);
    }

    //捕获处理不可预知异常
    @ExceptionHandler(Exception.class)
    public ResponseResult throwUnKownException(Exception e){
        LOGGER.error("excetion...{}",e.getMessage());
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }else{
            ResultCode resultCode = EXCEPTIONS.get(e.getClass());
            if(null != resultCode){
                return new ResponseResult(resultCode);
            }
        }
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }
}
